package com.neuedu.corejava.ch12;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 
 * @author myh
 * @version 2019年8月14日上午10:34:22
 *
 */
public class MyFileRead {

	public void copyAndFilter(String src, String desc) {
		if (src == null || desc == null) {
			return;
		}
		File srcFile = new File(src);
		File descFile = new File(desc);

		if (!srcFile.exists()) {
			return;
		}

		FileReader reader = null;
		FileWriter writer = null;
		BufferedReader br = null;
		try {
			if (!descFile.exists()) {
				descFile.getParentFile().mkdirs();
				descFile.createNewFile();
			}
			reader = new FileReader(srcFile);
			br = new BufferedReader(reader);
			writer = new FileWriter(descFile,false);

			String data = null;
			while ((data = br.readLine()) != null) {
				String newdata = data.replaceAll("l", "L");
				writer.write(newdata);
				writer.write("\r\n");
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
				}
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
				}
			}
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
				}
			}
		}

	}

	/**
	 * 把一段文本内容写入到一个指定文件中
	 * 
	 * @param filename
	 * @param content
	 */
	public void writeFile(String filename, String content) {
		if (filename == null) {
			return;
		}
		File file = new File(filename);
		FileOutputStream fos = null;
		try {
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			// 文件写入有两种模式：重写false，追加true
			fos = new FileOutputStream(file, false);
			// 需要把字符串转换成字节数组，准换时需要注意可能产生乱码
			fos.write(content.getBytes());			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public static void main(String[] args) {
		MyFileRead mfr = new MyFileRead();
		mfr.writeFile("c:\\test.txt", "hello world");
		System.out.println("新增成功");
		
		mfr.copyAndFilter("c:\\test.txt", "c:\\test2.txt");

	}

}
